package com.hsy.order.login.action

import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import com.flux.action.SubscriptionManager
import com.flux.dispatcher.Dispatcher
import com.flux.utils.GsonUtil
import com.hsy.order.base.action.ActionType
import com.hsy.order.base.action.BaseActionCreator
import com.hsy.order.base.action.BaseParam
import com.hsy.order.base.action.Key
import com.hsy.order.base.http.RetrofitFactory
import com.hsy.order.login.data.LoginResult

/**
 * 登录注册行为生成器
 * Created on 2017/12/4.
 *
 * @author Yang
 */
class LoginActionCreator(dispatcher: Dispatcher, manager: SubscriptionManager) : BaseActionCreator(dispatcher, manager) {

    private val service = RetrofitFactory.getService(LoginService::class.java)

    /**
     * 登录
     */
    fun login(user_name: String, user_password: String) {
        val action = newAction(ActionType.LOGIN)
        val params = LoginParams(user_name, user_password)
        service.login(params.toMap())
                .subscribeOn(Schedulers.io())
                .map { response ->
                    val string = response.string()
                    GsonUtil.getObject(string)
                }
                .filter { json -> checkResult(json.get("error").asString, "0", json.get("msg").asString) }
                .map { json -> GsonUtil.fromJson(json.get("result").toString(), LoginResult::class.java) }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ result ->
                    action.data[Key.LOGIN_RESULT] = result
                    action.data[Key.LOGIN_TOKEN] = result!!.token
                    postRxAction(action)
                }, { throwable ->
                    handleHttpError(throwable)
                    action.success = false
                    postRxAction(action)
                })
    }
}